package app.dwm;

import app.dwd.BaseAppFollow;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import common.Constant;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.PatternTimeoutFunction;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.shaded.curator4.org.apache.curator.shaded.com.google.common.base.Strings;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.OutputTag;
import util.GmallSinkUtil;

import java.time.Duration;
import java.util.List;
import java.util.Map;


public class DWMJumpDetailFollow extends BaseAppFollow {

    public static void main(String[] args) {
        new DWMJumpDetailFollow().init(4007, 1, "DWMJumpDetailFollow", Constant.TOPIC_DWD_PAGE_LOG, "DWMJumpDetailFollow");
    }

    //需求: 求用户跳出率
    //思路: 用户分组  水印   + cep模式匹配
    @Override
    public void run(StreamExecutionEnvironment env, DataStreamSource<String> dataStreamSource) {

        KeyedStream<JSONObject, String> readyToCEPStream = dataStreamSource
            .map(JSON::parseObject)
            .assignTimestampsAndWatermarks(WatermarkStrategy
                                               .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                               .withTimestampAssigner((obj, ts) -> obj.getLong("ts")))
            .keyBy(obj -> obj.getJSONObject("common").getString("mid"));
        //cep准备规则  ---> 规则作用在流 ---> 流中取出符合规则的值
        Pattern<JSONObject, JSONObject> pattern = Pattern
            .<JSONObject>begin("entry")
            .where(new SimpleCondition<JSONObject>() {
                @Override
                public boolean filter(JSONObject value) throws Exception {
                    String lastPageId = value.getJSONObject("page").getString("last_page_id");
                    return Strings.isNullOrEmpty(lastPageId);
                }
            })
            .next("entry2")
            .where(new SimpleCondition<JSONObject>() {
                @Override
                public boolean filter(JSONObject value) throws Exception {
                    String lastPageId = value.getJSONObject("page").getString("last_page_id");
                    return Strings.isNullOrEmpty(lastPageId);
                }
            })
            .within(Time.seconds(20));

        PatternStream<JSONObject> patternStream = CEP.pattern(readyToCEPStream, pattern);

        SingleOutputStreamOperator<JSONObject> cepedStream = patternStream.select(
            new OutputTag<JSONObject>("laterTag") {
            },
            new PatternTimeoutFunction<JSONObject, JSONObject>() {
                @Override
                public JSONObject timeout(Map<String, List<JSONObject>> pattern, long timeoutTimestamp) throws Exception {
                    return pattern.get("entry").get(0);
                }
            }
            , new PatternSelectFunction<JSONObject, JSONObject>() {
                @Override
                public JSONObject select(Map<String, List<JSONObject>> pattern) throws Exception {
                    return pattern.get("entry").get(0);
                }
            }
        );

        DataStream<JSONObject> late = cepedStream.getSideOutput(new OutputTag<JSONObject>("laterTag") {
        });
        GmallSinkUtil.sendToKafka(cepedStream.union(late).map(JSON::toString), Constant.TOPIC_DWM_USER_JUMP_DETAIL);
    }
}
